package com.sma.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.sma.pojo.Transaction;
import com.sma.validator.TransactionValidator;

@Controller
@RequestMapping("/validate")
public class ValidateController {

    // 表单页面
    @RequestMapping("/form")
    public ModelAndView formPage() {
        return new ModelAndView("validation");
    }

    /**
     * Spring验证（JSR 303）
     * @param trans 交易
     * @param errors 错误
     * @return
     */
    @RequestMapping("/annotation")
    public ModelAndView annotationValidate(@Valid Transaction trans, Errors errors) {
        ModelAndView mv = new ModelAndView();
        // 是否存在错误
        if (errors.hasErrors()) {
            // 获取错误信息
            List<FieldError> errorList = errors.getFieldErrors();
            for (FieldError error : errorList) {
                // 获取错误信息
                mv.addObject(error.getField(), error.getDefaultMessage());
            }
        }
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    @InitBinder
    public void initBinder(DataBinder binder) {
        //数据绑定器加入验证器
        binder.setValidator(new TransactionValidator());
    }

    @RequestMapping("/validator")
    public ModelAndView validator(@Valid Transaction trans, Errors errors) {
        ModelAndView mv = new ModelAndView();
        //是否存在错误
        if (errors.hasErrors()) {
            //获取错误信息
            List<FieldError>errorList = errors.getFieldErrors();
            for (FieldError error : errorList) {
                // 获取错误信息
                mv.addObject(error.getField(), error.getDefaultMessage());
            }
        }
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }
}
